﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Text;
using System.Data;
using GPSTracker.Views.DAL;
using GPSTracker.Helper;
using System.Xml;
using DevExpress.Web.ASPxEditors;
using System.Data.SqlClient;

namespace GPSTracker.Views.Delivery
{
    public partial class DeliveryEntry : System.Web.UI.Page
    {
        private DeliveryEntryDAL objDeliveryEntryDAL = new DeliveryEntryDAL();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    dtpOrderDate.Value = DateTime.Now;
                    dtpBillDate.Value = DateTime.Now;
                    BindWarehouseMaster();
                    BindBranchMaster();
                    BindAreaMaster();
                    txtVoucherNo.Focus();
                    
                    if (Request.QueryString["MODE"] != string.Empty && Request.QueryString["MODE"] != null)
                    {
                        btnUpdate.Visible = true;
                        btnSave.Visible = false;

                        if (Request.QueryString["MODE"] == "EDIT")
                        {
                            if (Session["DeliveryEntryID"] != string.Empty && Session["DeliveryEntryID"] != null)
                            {
                                hdnDeliveryEntry.Value = Session["DeliveryEntryID"].ToString();
                                GetOrderNoDetails(true, Session["DeliveryEntryID"].ToString());
                            }
                        }
                    }
                    else
                    {
                        btnUpdate.Visible = false;
                        btnSave.Visible = true;

                        if (Session["LoginMaster"] != "" && Session["LoginMaster"] != null)
                        {
                            var lg = Session["LoginMaster"] as Views.DAL.LoginBO;

                            if (lg.WarehouseID != 0)
                            {
                                cmbWarehouse.Value = lg.WarehouseID.ToString();
                                cmbWarehouse.ReadOnly = true;
                            }
                            else
                            {
                                cmbWarehouse.SelectedIndex = 0;
                                cmbWarehouse.ReadOnly = false;
                            }

                            if (lg.BranchID != 0)
                            {
                                cmbBranch.Value = lg.BranchID.ToString();
                                cmbBranch.ReadOnly = true;
                            }
                            else
                            {
                                cmbBranch.SelectedIndex = 0;
                                cmbBranch.ReadOnly = false;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "Page_Load");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void cmb_DataBound(object sender, EventArgs e)
        {
            var list = sender as ASPxComboBox;
            var lEi = new ListEditItem();
            lEi.Text = "--Select--";
            if (list != null)
            {
                list.Items.Insert(0, lEi);
            }
            list.SelectedIndex = 0;
        }

        public void BindWarehouseMaster()
        {
            try
            {
                var dt = new DataTable();
                dt = objDeliveryEntryDAL.FillWarehouseMaster();

                if (dt.Rows.Count > 0)
                {
                    cmbWarehouse.DataSource = dt;
                    cmbWarehouse.TextField = "WhouseNo";
                    cmbWarehouse.ValueField = "WhouseID";
                    cmbWarehouse.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "BindWarehouseMaster");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindBranchMaster()
        {
            try
            {
                var dt = new DataTable();
                dt = objDeliveryEntryDAL.FillBranchMaster();
                if (dt.Rows.Count > 0)
                {
                    cmbBranch.DataSource = dt;
                    cmbBranch.TextField = "BranchCode";
                    cmbBranch.ValueField = "BranchID";
                    cmbBranch.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "BindBranchMaster");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindAreaMaster()
        {
            try
            {
                var dt = new DataTable();
                dt = objDeliveryEntryDAL.FillAreaMaster();
                if (dt.Rows.Count > 0)
                {
                    cmbArea.DataSource = dt;
                    cmbArea.TextField = "AreaName";
                    cmbArea.ValueField = "AreaID";
                    cmbArea.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "BindAreaMaster");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData(false);
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "btnSave_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData(true);
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "btnUpdate_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        private bool SaveData(bool IsModify)
        {
            var settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.Entitize;
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new StringBuilder();

            try
            {
                var CmdSave = new SqlCommand();
                CmdSave.Connection = CommonFx.GetSqlCon();
                CmdSave.CommandType = CommandType.StoredProcedure;
                CmdSave.CommandText = "SP_InsertDeliveryEntry";

                using (var xw = XmlWriter.Create(sb, settings))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("CS");
                    xw.WriteStartElement("DeliveryEntry");
                    if (IsModify == true)
                    {
                        xw.WriteElementString("DeliveryEntryID", hdnDeliveryEntry.Value);
                    }

                    xw.WriteElementString("VoucherNo", txtVoucherNo.Text);
                    xw.WriteElementString("OrderNo", txtOrderNo.Text);
                    xw.WriteElementString("OrderDate", Convert.ToDateTime(dtpOrderDate.Value).ToString("yyyy-MMM-dd"));
                    xw.WriteElementString("BillNo", txtBillNo.Text);
                    xw.WriteElementString("BillDate", Convert.ToDateTime(dtpBillDate.Value).ToString("yyyy-MMM-dd"));
                    if(cmbWarehouse.Text != "--Select--" && cmbWarehouse.Text != string.Empty)
                    {
                        xw.WriteElementString("WhouseID", cmbWarehouse.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("WhouseID", "0");
                    }
                    if(cmbBranch.Text != "--Select--" && cmbBranch.Text != string.Empty)
                    {
                        xw.WriteElementString("BranchID", cmbBranch.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("BranchID", "0");
                    }
                    xw.WriteElementString("CustName", txtCustomerName.Text);
                    xw.WriteElementString("Address1", txtAddress1.Text);
                    xw.WriteElementString("Address2", txtAddress2.Text);
                    xw.WriteElementString("Address3", txtAddress3.Text);
                    xw.WriteElementString("Address4", txtAddress4.Text);
                    xw.WriteElementString("City", txtCity.Text);
                    xw.WriteElementString("Pincode", txtPincode.Text);
                    if(cmbArea.Text != "--Select--" && cmbArea.Text != string.Empty)
                    {
                        xw.WriteElementString("AreaID", cmbArea.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("AreaID", "0");
                    }
                    xw.WriteElementString("ContactNo", txtContactNo.Text);
                    xw.WriteElementString("EmailID", txtEmailID.Text);
                    xw.WriteElementString("MODEL_CODE", txtModelCode.Text);
                    xw.WriteElementString("MODEL_TYPE", txtModelType.Text);
                    xw.WriteElementString("ITEM_DESC", txtItemDescription.Text);                    
                    xw.WriteElementString("CHASIS_WISE", "0");
                    xw.WriteElementString("CHASIS_NO", txtChasisNo.Text);
                    xw.WriteElementString("Qty", txtQuantity.Text);
                    
                    xw.WriteElementString("Qty", txtQuantity.Text);
                    
                    xw.WriteEndElement();
                    xw.WriteEndDocument();
                    xw.Close();
                }

                CmdSave.Parameters.Add(new SqlParameter("@pXML", sb.ToString()));
                CmdSave.Parameters.Add(new SqlParameter("@pLoginID", (Session["LoginMaster"] as Views.DAL.LoginBO).LoginID));

                if (IsModify == false)
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", false));
                }
                else
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", true));
                }

                CmdSave.Parameters.Add("@pIsErrorFound", SqlDbType.Bit);
                CmdSave.Parameters.Add("@pErrorMessage", SqlDbType.NVarChar, 4000);
                CmdSave.Parameters.Add("@pDeliveryEntryID", SqlDbType.Int);

                CmdSave.Parameters["@pIsErrorFound"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pErrorMessage"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pDeliveryEntryID"].Direction = ParameterDirection.Output;

                CmdSave.ExecuteNonQuery();
                var strError = string.Empty;
                var str = CmdSave.Parameters["@pIsErrorFound"].Value.ToString();
                if (!Convert.ToBoolean(CmdSave.Parameters["@pIsErrorFound"].Value))
                {
                    if (IsModify == false)
                    {
                        strError = string.Empty;
                        lblMessage.Visible = true;
                        lblMessage.Text = "Delivery Entry Inserted Successfully.";

                        ScriptManager.RegisterStartupScript(UpMain, typeof(Page), "message", "Fade('" + lblMessage.ClientID + "');", true);
                        ClearPage();
                        txtOrderNo.Focus();
                    }
                    else
                    {
                        strError = string.Empty;
                        lblMessage.Text = "Delivery Entry Updated Successfully.";
                        Response.Redirect("ViewDeliveryEntry.aspx");
                    }

                    return true;
                }
                else
                {
                    if (IsModify == false)
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                    }
                    else
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "SaveData");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
                return false;
            }
        }

        public void ClearPage()
        {
            txtOrderNo.Text = string.Empty;
            dtpOrderDate.Value = DateTime.Now;
            txtBillNo.Text = string.Empty;
            dtpBillDate.Value = DateTime.Now;
            cmbWarehouse.Items.Clear();
            BindWarehouseMaster();
            cmbBranch.Items.Clear();
            BindBranchMaster();
            cmbArea.Items.Clear();
            BindAreaMaster();
            txtCustomerName.Text = string.Empty;            
            txtAddress1.Text  = string.Empty;
            txtAddress2.Text  = string.Empty;
            txtAddress3.Text = string.Empty;
            txtAddress4.Text = string.Empty;
            txtCity.Text = string.Empty;
            txtPincode.Text = string.Empty;
            txtContactNo.Text = string.Empty;
            txtEmailID.Text = string.Empty;
            txtModelCode.Text = string.Empty;
            txtModelType.Text = string.Empty;
            txtItemDescription.Text = string.Empty;
            txtChasisNo.Text = string.Empty;                                    
            txtQuantity.Text = string.Empty;
        }

        protected void txtOrderNo_TextChanged(object sender, EventArgs e)
        {
            try
            {
                
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "txtOrderNo_TextChanged");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void txtVoucherNo_TextChanged(object sender, EventArgs e)
        {
            try
            {
                lblMessage.Text = string.Empty;
                if (txtVoucherNo.Text != string.Empty)
                {
                    if (Request.QueryString["MODE"] != string.Empty && Request.QueryString["MODE"] != null)
                    {
                        if (Request.QueryString["MODE"] == "EDIT")
                        {
                        }
                    }
                    else
                    {
                        GetOrderNoDetails(false, txtVoucherNo.Text);
                    }
                }
                txtOrderNo.Focus();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "txtVoucherNo_TextChanged");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void GetOrderNoDetails(bool IsEditMode, string strVoucherNo)
        {
            try
            {
                var dt = new DataTable();
                var sb = new StringBuilder();
                if (IsEditMode == false)
                {
                    sb.Append("SELECT * FROM VW_GetDeliveryEntry WHERE VoucherNo = '" + strVoucherNo + "' ");
                }
                else
                {
                    sb.Append("SELECT * FROM VW_GetDeliveryEntry WHERE DeliveryEntryID = '" + strVoucherNo + "' ");
                }

                var cmd = new SqlCommand(sb.ToString(), CommonFx.GetSqlCon());
                var da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    txtOrderNo.Text = dt.Rows[0]["OrderNo"].ToString();
                    dtpOrderDate.Value = Convert.ToDateTime(dt.Rows[0]["OrderDate"]);
                    txtBillNo.Text = dt.Rows[0]["BillNo"].ToString();
                    dtpBillDate.Value = Convert.ToDateTime(dt.Rows[0]["BillDate"]);
                    cmbWarehouse.Value = dt.Rows[0]["WhouseID"].ToString();
                    cmbBranch.Value = dt.Rows[0]["BranchID"].ToString();
                    txtCustomerName.Text = dt.Rows[0]["CustName"].ToString();
                    txtAddress1.Text = dt.Rows[0]["Address1"].ToString();
                    txtAddress2.Text = dt.Rows[0]["Address2"].ToString();
                    txtAddress3.Text = dt.Rows[0]["Address3"].ToString();
                    txtAddress4.Text = dt.Rows[0]["Address4"].ToString();
                    txtCity.Text = dt.Rows[0]["City"].ToString();
                    txtPincode.Text = dt.Rows[0]["Pincode"].ToString();
                    cmbArea.Value = dt.Rows[0]["AreaID"].ToString();                    
                    txtContactNo.Text = dt.Rows[0]["ContactNo"].ToString();
                    txtEmailID.Text = dt.Rows[0]["EmailID"].ToString();

                    if (IsEditMode == true)
                    {
                        txtVoucherNo.Text = dt.Rows[0]["VoucherNo"].ToString();
                        txtModelCode.Text = dt.Rows[0]["MODEL_CODE"].ToString();
                        txtModelType.Text = dt.Rows[0]["MODEL_TYPE"].ToString();
                        txtItemDescription.Text = dt.Rows[0]["ITEM_DESC"].ToString();
                        txtChasisNo.Text = dt.Rows[0]["CHASIS_NO"].ToString();
                        txtQuantity.Text = dt.Rows[0]["Qty"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "GetOrderNoDetails");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                ClearPage();
                txtOrderNo.Focus();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Delivery Entry", "btnClear_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }





        //-- CODE END
    }
}
